#include "editform.h"
#include "ui_editform.h"

#include <QSqlQuery>
#include <QMessageBox>
#include <QDate>
#include <QDebug>

EditForm::EditForm(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::EditForm)
{
    ui->setupUi(this);
}

EditForm::~EditForm()
{
    delete ui;
}

void EditForm::on_pushButtonCancel_clicked()
{
    this->deleteLater();
}


void EditForm::on_pushButtonAccept_clicked()
{
    QSqlQuery q;
    q.prepare("SELECT consumeTime, startTime FROM projects WHERE id = ?");
    q.addBindValue(ui->lineEditProjectID->text());
    if (q.exec() && q.next())
    {
        int newDays = ui->lineEditConsumeTime->text().toInt();

        qDebug() << q.value(1).toString();
        QDate startTime = QDate::fromString(q.value(1).toString(), "yyyy年M月d日");
        qDebug() << startTime.toString();
        QDate newEndDate = startTime.addDays(newDays);


        QSqlQuery q;
        q.prepare("UPDATE projects SET consumeTime = ?, endTime = ? WHERE id = ?");
        q.addBindValue(newDays);
        q.addBindValue(newEndDate.toString("yyyy年M月d日"));
        q.addBindValue(ui->lineEditProjectID->text());

        if (q.exec()) {
            QMessageBox::information(this, "成功", "更新成功");
        } else {
            QMessageBox::critical(this, "错误", "更新失败");
        }
    }
    else
    {
        QMessageBox::warning(this, "错误", "ID输入错误");
    }
    this->parentWidget()->hide();
    this->parentWidget()->show();
    this->deleteLater();
}


void EditForm::on_lineEditProjectID_textChanged(const QString &arg1)
{
    QSqlQuery q;
    q.prepare("SELECT consumeTime FROM projects WHERE id = ?");
    q.addBindValue(ui->lineEditProjectID->text());
    if (q.exec() && q.next()) {
        ui->lineEditConsumeTime->setText(q.value(0).toString());
    }
    else
    {
        ui->lineEditConsumeTime->setText("");
    }
}

